<?php

namespace addons\yungift\controller;

use addons\yungift\library\Constant;
use addons\yungift\library\Logic;
use addons\yungift\library\Super;
use addons\yungift\model\CardCode;
use addons\yungift\model\CardMain;
use addons\yungift\model\Config;
use addons\yungift\model\GiftCode;
use addons\yungift\model\GiftMain;
use addons\yungift\model\GiftOrder;
use addons\yungift\model\GiftSpec;
use addons\yungift\model\Norepeat;
use addons\yungift\model\UserAuth;
use addons\yungift\model\SmsCode;
use app\common\model\User;
use app\common\controller\Api;
use fast\Random;
use think\Db;
use think\Env;
use think\Exception;
use think\exception\PDOException;
use think\Validate;


/**
 * 礼卡接口
 */
class Preview extends Api
{
    protected $noNeedRight = ['*'];
    protected $noNeedLogin = ['*'];

    protected $platform;
    protected $cardId;
    protected $cardData;
    protected $cardCodeId;
    protected $cardCodeData;

    /**
     * 初始化操作
     * @access protected
     */
    protected function _initialize()
    {
        parent::_initialize();

        // 跨域请求检测
        check_cors_request();

        $cardPreKey = input('get.card_pre_key');
        $flag = input('get.flag');
        $cardId = input('get.card_id');
        if (empty($cardPreKey) || empty($flag) || empty($cardId)) {
            $this->error(__('缺少参数'),  null, Constant::INVALID_CARD);
        }
        
        // 校验预览的参数
        $prevKey = Env::get('misc.prevKey');
        $sign = md5($cardId . $flag . $prevKey);
        $cardPreKey = base64_decode($cardPreKey);
        if ($sign != $cardPreKey) {
            $this->error(__('参数不合法'),  null, Constant::INVALID_CARD);
        }
        if ($flag < time()) {
            $this->error(__('预览链接已失效'),  null, Constant::INVALID_CARD);
        }

        // 礼卡数据
        $this->cardData = CardMain::where(['id' => $cardId])->show()->find();
        if (! $this->cardData) {
            $this->error(__('活动已停止或没有参与权限'), null, Constant::INVALID_CARD);
        }
        $this->cardId = $this->cardData->id;
    }


    // 获取整体数据
    public function getWrapDataPre()
    {
        // 礼卡数据
        $cardData = Super::arrayGetSet($this->cardData, ['home_top_img', 'content', 'state']);


        // 已兑礼品
        $giftIds = [];
        // 全部礼品
        $giftList = GiftMain::where(['status' => GiftMain::STATUS_NORMAL])
            ->where('find_in_set(:aid, `card_ids`)', ['aid' => $this->cardData->id])
            ->where('start_time', ['>', 0], ['<=', time()], 'and')
            ->where('end_time', ['>', 0], ['>', time()], 'and')
            ->order('weight DESC, id DESC')->select();
        $giftList = Super::arrayGetSet($giftList, [
            'id',
            'type',
            'name',
            'cover_url',
            'worth',
            'amount',
            'multi_spec',
            'count_left',
            'count_gain',
            'state' => function ($item) use ($giftIds) {
                return in_array($item->id, $giftIds) ? 2 : 1;
            },
            'created_at',
        ], true);

        $this->success('操作成功', compact('cardData', 'giftList'));
    }

    // 获取礼品详情
    public function getDetailPre()
    {
        $giftId = $this->request->get('id');
        $gift = $this->validGift($giftId);

        $result = Super::arrayGetSet($gift, [
            'id',
            'type',
            'name',
            'cover_url',
            'photo_list',
            'content',
            'worth',
            'amount',
            'multi_spec',
            'count_left',
            'count_gain',
            'external_link',
            'created_at',
        ]);
        if ($gift->multi_spec) {
            if (! $giftSpecList = $gift->giftSpecListData) {
                $this->error('礼品数据无效，缺少规格');
            }
            $result['spec_list'] = Super::arrayGetSet($giftSpecList, [
                'id',
                'name',
                'worth',
                'amount',
                'count_left',
                'count_gain'
            ], true);
            $result['order_worth'] = $giftSpecList[0]->worth;
        } else {
            $result['spec_list'] = null;
            $result['order_worth'] = $gift->worth;
            $result['order_amount'] = $gift->amount;
        }
        $orderState = 0;
        $result['order_state'] = $orderState;

        $this->success('success', $result);
    }


    /**
     * 校验礼品
     *
     * @param $giftId
     * @return GiftMain
     */
    private function validGift($giftId)
    {
        if (! $gift = GiftMain::get($giftId)) {
            $this->error('礼品无效');
        }
        if ($gift->status != GiftMain::STATUS_NORMAL) {
            $this->error('礼品已下架');
        }
        if (($gift->start_time && $gift->start_time > time()) || ($gift->end_time && $gift->end_time <= time())) {
            $this->error('礼品已下架');
        }
        $activityIds = $gift->card_ids ? explode(',', $gift->card_ids) : [];
        if (! in_array($this->cardId, $activityIds)) {
            $this->error('礼品不在礼卡内');
        }

        return $gift;
    }
}
